const NOT_TOKEN = -21;
const INVALID_TOKEN = -22;
const TOKEN_TIMEOUT = -23;
const BE_REPLACED = -24;
const KICK_OUT = -25;
const NO_LOGIN = -20;

const YES = 1;
const NO = 0;

const YES_NO_PROP = ["否", "是"];

const IMPORT_ERROR = 500;
const IMPORT_WARN = 501;

const CUSTOMER_CATEGORY_KEY = "customer_category";
const CUSTOMER_TYPE_KEY = "customer_type";
const CUSTOMER_PATTERN_KEY = "customer_pattern";
const DEALER_LEVEL_KEY = "dealer_level";
const TARGET_CUSTOMER_TYPE_KEY = "target_customer_type";
const PRODUCT_UNIT_KEY = "product_unit";
const PRODUCT_TYPE_KEY = "product_type";
const PRODUCT_SPEC_KEY = "product_spec";

const COMMERCIAL_CATEGORY_ID = 51;

const AREA_CODE_LEN = 5;
const CHECK_AREA_LEVEL = 2;

function myAjax(jquery, layer, opt, showLoad) {
	var idx;
	if (showLoad != false) {
		idx = layer.load(0, {content: "请稍候……", shade: 0.4});
	}
	jquery.ajax({
		url: opt.url || "/",
		type: opt.type || "POST",
		data: opt.data || {},
		dataType: opt.dataType || "json",
		success: function (d, s) {
			if (checkRet(layer, d)) {
				opt.success && opt.success(d, s);
			}
		},
		err: function (XMLHttpRequest, textStatus, err) {
			layer.msg('对不起，发生错误!', {icon: 2, time: 1500});
		},
		complete: function (XMLHttpRequest, textStatus) {
			if (showLoad != false) {
				layer.close(idx);
			}
			opt.complete && opt.complete(XMLHttpRequest, textStatus);
		}
	});
}

/**
 * 初始化导入模块
 * @param layui
 * @param para.templet 导入模板下载地址
 * @param para.import 导入提交地址
 * @param para.table 导入目标数据表格，用于导入完成后刷新数据
 */
function initImport(layui, para) {
	var $ = layui.jquery,
		layer = layui.layer,
		form = verifyForm(layui.form);
	var importIdx;
	var importForm = $('<form class="layui-form layui-form-pane"id="importForm"lay-filter="importForm"style="display: none;padding:5px"><div class="layui-form-item"widthoffset="10"><div class="layui-inline"><div class="layui-input-block  col12"><div class="layui-upload-drag"id="upload"><i class="layui-icon"></i><p>点击上传，或将文件拖拽到此处</p></div></div></div></div><div class="layui-form-item"widthoffset="10"><div class="layui-input-block  col6"><button type="button"class="layui-btn"id="template"><i class="layui-icon layui-icon-download-circle"></i>下载模板</button></div></div></div></form>');
	$("body").append(importForm);
	if (!para.noOverWrite) {
		$("#importForm").append($('<div class="layui-form-item"widthoffset="10"><div class="layui-inline"><label class="layui-form-label required">数据覆盖</label><div class="layui-input-block  col12"><input type="checkbox"name="overwrite"lay-skin="switch"lay-text="是|否"value="1"></div></div></div>'));
	}
	form.render('checkbox');
	$("#import").click(function () {
		importIdx = layerForm(layer, $, {
			title: '导入',
			content: importForm,
			type: 1,
			area: "300px",
			shade: 0.2,
			maxmin: false,
			shadeClose: true,
		});
	});
	$("#template").click(function () {
		window.open(para.templet);
	});

	myImportRend(layui, {
		elem: '#upload',
		url: para.import,
		data: {
			update: function () {
				if (para.noOverWrite) {
					return 0;
				} else {
					var overwrite = form.val("importForm").overwrite;
					if (!overwrite) {
						overwrite = 0;
					}
					return overwrite;
				}
			}
		},
		done: function (res, index, upload) {
			layer.close(importIdx);
			para.table.reload();
		}
	});
}

function myImportRend(layui, para) {
	var $ = layui.jquery,
		layer = layui.layer,
		upload = layui.upload,
		table = layui.table;
	upload.render({
		elem: para.elem,
		url: para.url,
		data: para.data,
		accept: 'file',
		exts: 'xlsx|xls',
		acceptMime: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
			layer.load(0, {content: "请稍候……", shade: 0.4});//上传loading
		},
		error: function (index, upload) {
			layer.closeAll('loading'); //关闭loading
		},
		done: function (res, index, upload) { //上传后的回调
			layer.closeAll('loading'); //关闭loading
			if (checkRet(layer, res)) {
				if (res && res.code == IMPORT_ERROR) {
					var resForm = $("#importResForm");
					if (resForm.length <= 0) {
						resForm = $('<form class="layui-form layui-form-pane" id="importResForm" lay-filter="importResForm" style="display: none;padding:5px"><table class="layui-hide" id="importTable" lay-filter="importTable"></table></form>');
						$("body").append(resForm);
					}
					layer.open({
						title: '导入结果',
						content: resForm,
						type: 1,
						area: ["500px", "400px"],
						shade: 0.2,
						maxmin: true,
						shadeClose: false
					});
					table.render({
						elem: '#importTable',
						data: res.data,
						cols: [[
							{
								field: 'data', title: '行号', width: 60, align: "center",
								templet: function (d) {
									return d.data + 1;
								}
							},
							{
								field: 'code', title: '结果', width: 60, align: "center",
								templet: function (d) {
									if (d.code == IMPORT_WARN) {
										return '<span style="color: #00f;">警告</span>'
									} else {
										return '<span style="color: #f00;">失败</span>'
									}
								}
							},
							{field: 'msg', title: '详情', align: "center"}
						]],
						limit: res.data.length,
						page: false,
						skin: 'line'
					});
				} else {
					layer.msg('导入成功', {icon: 1, time: 1500});
				}
			}
			para.done && para.done(res, index, upload);
		}
	});
}

function myTableRend(table, layer, para) {
	var pd = para.parseData;
	para.parseData = function (res) { //res 即为原始返回的数据
		if (checkRet(layer, res)) {
			if (para.formatDate) {
				for (let d of res.data) {
					for (let fd of para.formatDate) {
						if (d[fd]) {
							d[fd] = d[fd].substr(0, 10);
						}
					}
				}
			}
			if (pd) {
				return pd(res);
			} else {
				return res;
			}
		} else {
			if (!res.msg) {
				res.msg = "";
			}
			return {
				code: -1,
				msg: "对不起，发生错误！" + res.msg
			};
		}
	};
	return table.render(para);
}

function myTreeTableRend(treetable, layer, para) {
	layer.load(0, {content: "请稍候……", shade: 0.4});
	var done = para.done;
	para.parseData = function (res) { //res 即为原始返回的数据
		if (checkRet(layer, res)) {
			return res;
		} else {
			if (!res.msg) {
				res.msg = "";
			}
			return {
				code: -1,
				msg: "对不起，发生错误！" + res.msg
			};
		}
	};
	para.done = function () {
		layer.closeAll('loading');
		done && done();
	};
	return treetable.render(para);
}

function checkRet(layer, d) {
	if (d) {
		if (d.code == -1) {
			layer.msg('对不起，发生错误！' + d.msg, {icon: 2, time: 1500});
		} else if (d.code == NOT_TOKEN || d.code == NO_LOGIN) {
			layer.msg('对不起，请先登录！', {icon: 2, time: 1500}, function () {
				top.location = '/login.html';
			});
		} else if (d.code == INVALID_TOKEN) {
			layer.msg('对不起，登录无效，请先登录！', {icon: 2, time: 1500}, function () {
				top.location = '/login.html';
			});
		} else if (d.code == TOKEN_TIMEOUT) {
			layer.msg('对不起，登录超时，请先登录！', {icon: 2, time: 1500}, function () {
				top.location = '/login.html';
			});
		} else if (d.code == BE_REPLACED) {
			layer.msg('对不起，账户已在其他设备登录！', {icon: 2, time: 1500}, function () {
				top.location = '/login.html';
			});
		} else if (d.code == KICK_OUT) {
			layer.msg('对不起，您已被管理员强制下线！', {icon: 2, time: 1500}, function () {
				top.location = '/login.html';
			});
		} else {
			return true;
		}
	} else {
		layer.msg('对不起，发生错误！', {icon: 2, time: 1500});
	}
	return false;
}

function submitLayerForm(filter, url, action, dataTable, frmIdx, layui, done) {
	verifyForm(layui.form).on('submit(' + filter + ')', function (data) {
		myAjax(layui.$, layer, {
			url: url,
			type: 'POST',
			data: data.field,
			dataType: "json",
			success: function (d, s) {
				if (d.code == 1) {
					layer.msg(action + '成功', {icon: 1, time: 1500});
					dataTable.reload();
					done && done(d);
					// setTimeout(function () {
					// 	dataTable.reload();
					// }, 1500);
				}
			},
			complete: function (xhr, status) {
				layer.close(frmIdx);
			}
		});
		return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});
}

function verifyForm(form) {
	form.verify({
		positiveInteger: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (value.indexOf(".") != -1) {
					return '请输入整数';
				} else {
					if (/^-?\d+$/.test(value)) {
						if (parseInt(value) < 0) {
							return '请输入正数';
						}
					} else {
						return '请输入数字';
					}
				}
			}
		},
		positiveDouble: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (/^-?[1-9]+(\.\d+)?$|-?^0(\.\d+)?$|-?^[1-9]+[0-9]*(\.\d+)?$/.test(value)) {
					if (parseFloat(value) < 0) {
						return '请输入正数';
					}
				} else {
					return '请输入数字';
				}
			}
		},
		telephone: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (!/(^(\+\d{2}[-_－—])?0\d{2,3}[-_－—]\d{7,8}$)|(^(\d{3,4}[-_－—])?\d{7,8})$|(13[0-9]{9})/.test(value)) {
					return '电话号码格式不正确';
				}
			}
		},
		fax: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (!/^(\d{3,4}-)?\d{7,8}$/.test(value)) {
					return '传真格式不正确';
				}
			}
		},
		postCode: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (!/^[1-9]\d{5}$/.test(value)) {
					return '邮政编码格式不正确';
				}
			}
		},
		idCard: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (!/^(\d{18}|\d{15}|\d{17}x)$/.test(value)) {
					return '身份证号格式不正确';
				}
			}
		},
		Email: function (value, item) { //value：表单的值、item：表单的DOM对象
			if (value.trim()) {
				if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
					return '邮箱格式不正确';
				}
			}
		}
	});
	return form;
}

//按钮分散对齐
function locateBtns(layero, $) {
	var layerBtns = layero.find(".layui-layer-btn a");
	var btns = layero.find(".btns .layui-btn");
	var sumWidth = 0;
	layui.each(layerBtns, function (i, e) {
		sumWidth += $(e).outerWidth();
	});
	var gap = (layero.width() - sumWidth) / (layerBtns.length + 1);
	layui.each(layerBtns, function (i, e) {
		$(e).css({
			position: "relative",
			left: gap * (i + 1)
		});
	});
	sumWidth = 0;
	layui.each(btns, function (i, e) {
		sumWidth += $(e).outerWidth();
	});
	var pLeft = parseInt(layero.find(".layui-layer-wrap").css("padding-left"));
	var pRight = parseInt(layero.find(".layui-layer-wrap").css("padding-right"));
	gap = (layero.width() - pLeft - pRight - sumWidth) / (btns.length + 1);
	layui.each(btns, function (i, e) {
		$(e).css({
			position: "relative",
			left: gap * (i + 1)
		});
	});
}

//表单元素宽度自适应
function resizeForm(layero, $) {
	var items = layero.find(".layui-form-item");
	layui.each(items, function (i, e) {
		var widthoffset = $(e).attr("widthoffset");
		var widthSum = 0;
		layui.each($(e).find(".layui-form-label"), function (i, e) {
			widthSum += $(e).outerWidth(true);
		});
		layui.each($(e).find(".layui-input-inline[width]"), function (i, e) {
			var jdom = $(e);
			jdom.width(jdom.attr("width"));
			widthSum += jdom.outerWidth(true);
		});
		var totalWidth = $(e).width() - widthSum;
		if (widthoffset) {
			totalWidth -= widthoffset;
		}
		for (var i = 0; i < 12; i++) {
			var cells = $(e).find(".col" + (i + 1));
			cells.width(totalWidth * (i + 1) / 12);
		}
	});
	locateBtns(layero, $);
}

//入口方法，绑定事件并调用弹出层
function layerForm(layer, jquery, options) {
	var resizing = options.resizing;
	var full = options.full;
	var restore = options.restore;
	var success = options.success;
	var $ = jquery;
	options.btnAlign = "l";
	options.resizing = function (layero) {
		resizeForm(layero, $);
		resizing && resizing(layero);
	};
	options.full = function (layero) {
		resizeForm(layero, $);
		full && full(layero);
	};
	options.restore = function (layero) {
		resizeForm(layero, $);
		restore && restore(layero);
	};

	options.success = function (layero, index) {
		resizeForm(layero, $);
		layero.keydown(function (e) {
			if (e.keyCode == 27) {
				layer.close(index);
			}
		});
		success && success(layero, index);
	};

	return layer.open(options);
}

Array.prototype.indexOf = function (val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};
Array.prototype.remove = function (val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};

//获取url中的参数
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); // 匹配目标参数
	var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
	if (result != null) {
		return decodeURIComponent(result[2]);
	} else {
		return null;
	}
}

/**
 * json转url参数
 * @param json
 */
function json2param(json) {
	return Object.keys(json).map(function (key) {
		return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
	}).join("&");
}

function uuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "";

	var uuid = s.join("");
	return uuid;
}

function getAreaTreeAndRend(layui, element, done, isNull) {
	getAreaTree(layui, function (d, s) {
		renderAreaTree(layui, element, d.data, done, isNull);
	});
}

function getAreaTree(layui, success) {
	myAjax(layui.$, layui.layer, {
		url: "/area/listTree",
		type: 'GET',
		dataType: "json",
		success: function (d, s) {
			success && success(d, s);
		}
	});
}

function renderAreaTree(layui, element, datas, done, isNull, on) {
	let xmSelectOptions = {
		el: element,
		name: "areaId",
		model: {label: {type: 'text'}},
		radio: true,//单选模式
		clickClose: true,//选中关闭
		tips: '请选择区域',
		filterable: true,
		toolbar: {
			show: true,
			list: ['CLEAR']
		},
		tree: {
			show: true,
			expandedKeys: true,
			strict: false
		},
		prop: {
			name: "title",
			value: "id",
			children: "children"
		},
		data: datas
	};
	if (on) {
		xmSelectOptions.on = on;
	}
	if (!isNull) {
		xmSelectOptions.layVerify = 'required';
		xmSelectOptions.layReqText = '请选择区域';
	}
	let areaDom = xmSelect.render(xmSelectOptions);
	done && done(areaDom, datas);
}

function findTreeNode(nodes, id) {
	for (let node of nodes) {
		if (node.id == id) {
			return node;
		}
	}
	for (let node of nodes) {
		if (node.children && node.children.length > 0) {
			let n = findTreeNode(node.children, id);
			if (n) {
				return n;
			}
		}
	}
}

function checkAreaLevel(area, level) {
	return area.code.length == (level + 1) * AREA_CODE_LEN;
}